<?php

class CoreAPI extends CoreController {

	function __construct()
	{
		parent::__construct();
		$this->loadComponent('jsonComponent');
	}

	public function responseData($status,$data)
	{
		echo jsonComponent::encodeData(array_merge(array('status'=>$status),$data));
		exit;
	}

	public function formatData($data,$key=null)
	{
		$dataFormat = array();
		foreach($data as $value){
			$dataFormat[(!empty($key) ? $key : "data")] = $value;
		}
		return $dataFormat;
	}

	public function extract($properties,$modifiers=array(),$ifExists=true)
	{
		foreach((array)$properties as $key=>$value){
			if(!empty($modifiers['key']) && is_callable($modifiers['key'])){
				$key = $modifiers['key']($key,$value);
			}
			if(!empty($modifiers['value']) && is_callable($modifiers['value'])){
				$value = $modifiers['value']($key,$value);
			}
			if(!$ifExists || ($ifExists && property_exists($this,$key))){
				$this->$key = $value;
			}
		}
	}

	public function validateUser($user,$token)
	{
		$userToUse = "dev_nav";
		$tokenToUse = "768e91876e22ae80eb41d54dbae3837f";
		if($user == $userToUse && $token == $tokenToUse){
			return true;
		}else{
			return false;
		}
	}

	/* Post Article API */

	public function getCategories($id,$post)
	{
		global $wp_rewrite;
		$categories = array();
		$cats = get_the_category($id);
		foreach($cats as $category){
			$categories[] = array(
				'id'=>$category->term_id,
				'name'=>$category->cat_name,
				'link'=>get_category_link($category->term_id)
			);
		}
		return $categories;
	}

	public function popularPosts($user,$token,$no_posts = 10, $show_pass_post = false, $duration=null) 
	{
		if(!empty($user) && !empty($token)){
			if($this->validateUser($user,$token)===true){
				$query = "SELECT *, COUNT(".$this->wpdb->comments.".comment_post_ID) AS comment_count FROM ".$this->wpdb->posts.", ".$this->wpdb->comments." WHERE comment_approved=1 AND ".$this->wpdb->posts.".ID = ".$this->wpdb->comments.".comment_post_ID AND post_status='publish'";
			    if($show_pass_post==true){ $query .= " AND post_password =''";}
			    if(!empty($duration)) { $query .= " AND DATE_SUB(CURDATE(),INTERVAL ".$duration." DAY) < post_date ";}
			    $query .= " GROUP BY ".$this->wpdb->comments.".comment_post_ID ORDER BY comment_count DESC LIMIT ".$no_posts;
			    $posts = $this->wpdb->get_results($query);
			    $data = array();
			    if(!empty($posts)){
			    	foreach($posts as $post){
			    		$data[] = array(
				    		'id'=>$post->ID,
							'author'=>array('id'=>$post->post_author,'name'=>get_the_author_meta('display_name',$post->post_author),'link'=>get_author_posts_url($post->post_author)),
							'date'=>$post->post_date,
							'title'=>$post->post_title,
							'content'=>rtrim(html_entity_decode($post->post_content)),
							'thumbnail'=>get_post_meta($post->ID, 'thumbnail', true),
							'status'=>$post->post_status,
							'slug'=>$post->post_name,
							'date_modified'=>$post->post_modified,
							'permalink'=>get_permalink($post->ID),
							'type'=>$post->post_type,
							'comments'=>$post->comment_count,
							'categories'=>$this->getCategories($post->ID,$post),
			    		);
			    	}
			    	$this->responseData(200,array_merge(array('success'=>true),array('posts'=>$data)));
			    }else{
			    	$this->responseData(200,array('success'=>false,'message'=>'No items'));
			    }
			}else{
				$this->responseData(200,array('success'=>false,'message'=>"Unauthorized: You don't permission"));
			}
		}else{
			$this->responseData(200,array('success'=>false,'message'=>'Parameter id is missing'));
		}
	}

	public function findPost($user,$token,$id)
	{
		if(!empty($user) && !empty($token)){
			if($this->validateUser($user,$token)===true){
				$post = get_post($id);
				if(!empty($post)){
					$data = array(
						'id'=>$post->ID,
						'author'=>array('id'=>$post->post_author,'name'=>get_the_author_meta('display_name',$post->post_author),'link'=>get_author_posts_url($post->post_author)),
						'date'=>$post->post_date,
						'title'=>$post->post_title,
						'content'=>rtrim(html_entity_decode($post->post_content)),
						'thumbnail'=>get_post_meta($post->ID, 'thumbnail', true),
						'status'=>$post->post_status,
						'slug'=>$post->post_name,
						'date_modified'=>$post->post_modified,
						'permalink'=>get_permalink($post->ID),
						'type'=>$post->post_type,
						'comments'=>$post->comment_count,
						'categories'=>$this->getCategories($post->ID,$post),
					);
					$this->responseData(200,array_merge(array('success'=>true),array('post'=>$data)));
				}else{
					$this->responseData(200,array('success'=>false,'message'=>'No items'));
				}
			}else{
				$this->responseData(200,array('success'=>false,'message'=>"Unauthorized: You don't permission"));
			}
		}else{
			$this->responseData(200,array('success'=>false,'message'=>'Parameter id is missing'));
		}
	}

	public function recentPosts($user,$token,$query)
	{
		global $wp_query;
		$data = array();
		if(!empty($user) && !empty($token)){
			if($this->validateUser($user,$token)===true){
				$recentPosts = wp_get_recent_posts($query,OBJECT);
				if(!empty($recentPosts)){
					foreach($recentPosts as $post){
						$data[] = array(
							'id'=>$post->ID,
							'author'=>array('id'=>get_the_author_meta('ID'),'name'=>get_the_author_meta('display_name'),'link'=>get_author_posts_url(get_the_author_meta('ID'))),
							'date'=>$post->post_date,
							'title'=>$post->post_title,
							'content'=>rtrim(html_entity_decode($post->post_content)),
							'excerpt'=>wp_strip_all_tags(html_entity_decode(str_replace("[&hellip;]","",apply_filters('the_excerpt', get_the_excerpt())))),
							'thumbnail'=>get_post_meta($post->ID, 'thumbnail', true),
							'status'=>$post->post_status,
							'slug'=>$post->post_name,
							'date_modified'=>$post->post_modified,
							'permalink'=>get_permalink($post->ID),
							'type'=>$post->post_type,
							'comments'=>$post->comment_count,
							'categories'=>$this->getCategories($post->ID,$post),
						);
					}
					$returnQuery = array('number_pages'=>$wp_query->max_num_pages,'posts'=>$data);
					$this->responseData(200,array_merge(array('success'=>true),$returnQuery));
				}else{
					$this->responseData(200,array('success'=>false,'message'=>'No items'));
				}
			}else{
				$this->responseData(200,array('success'=>false,'message'=>"Unauthorized: You don't permission"));
			}
		}else{
			$this->responseData(200,array('success'=>false,'message'=>'Parameter id is missing'));
		}
	}

	public function queryPosts($user,$token,$query)
	{
		global $wp_query;
		$data = array();
		if(!empty($user) && !empty($token)){
			if($this->validateUser($user,$token) === true){
				$getPosts = query_posts($query);
				if(!empty($getPosts)){
					foreach($getPosts as $post) {
						setup_postdata($post);
						$data[] = array(
							'id'=>$post->ID,
							'author'=>array('id'=>get_the_author_meta('ID'),'name'=>get_the_author_meta('display_name'),'link'=>get_author_posts_url(get_the_author_meta('ID'))),
							'date'=>$post->post_date,
							'title'=>$post->post_title,
							'content'=>rtrim(html_entity_decode($post->post_content)),
							'excerpt'=>wp_strip_all_tags(html_entity_decode(str_replace("[&hellip;]","",apply_filters('the_excerpt', get_the_excerpt())))),
							'thumbnail'=>get_post_meta($post->ID, 'thumbnail', true),
							'status'=>$post->post_status,
							'slug'=>$post->post_name,
							'date_modified'=>$post->post_modified,
							'permalink'=>get_permalink($post->ID),
							'type'=>$post->post_type,
							'comments'=>$post->comment_count,
							'categories'=>$this->getCategories($post->ID,$post),
						);
					}
					wp_reset_postdata();
					$returnQuery = array('number_pages'=>$wp_query->max_num_pages,'posts'=>$data);
					$this->responseData(200,array_merge(array('success'=>true),$returnQuery));
				}else{
					$this->responseData(200,array('success'=>false,'message'=>'No items'));
				}
			}else{
				$this->responseData(200,array('success'=>false,'message'=>"Unauthorized: You don't permission"));
			}
		}else{
			$this->responseData(200,array('success'=>false,'message'=>'Parameter id is missing'));
		}
	}

	/* Facebook */

	public function loginFaceBook($user,$password)
	{
		
	}

	public function registerFaceBook()
	{
		
	}

}